﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ToolUtil
{
    /// <summary>
    /// 字符串加密解密类
    /// </summary>
    public  class StringSecurity
    {
        #region Md5加密

        /// <summary>
        /// 获取字符串MD5加密字符串
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5加密字符串</returns>
        public static string GetMd5(string str)
        {
            var pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            return pwd;
        }

        /// <summary>
        /// 使用SHA1加密字符串。
        /// </summary>
        /// <param name="inputString">输入字符串。</param>
        /// <returns>加密后的字符串。（40个字符）</returns>
        public static string StringToSHA1Hash(string inputString)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] encryptedBytes = sha1.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }
        #endregion

        #region 可逆加密 解密

        private static byte[] key = ASCIIEncoding.ASCII.GetBytes("yjimspoi");
        private static byte[] iv = ASCIIEncoding.ASCII.GetBytes("99008855");

        /// <summary>
        /// DES加密。
        /// </summary>
        /// <param name="inputString">输入字符串。</param>
        /// <returns>加密后的字符串。</returns>
        public static string DESEncrypt(string inputString)
        {
            MemoryStream ms = null;
            CryptoStream cs = null;
            StreamWriter sw = null;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                ms = new MemoryStream();
                cs = new CryptoStream(ms, des.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                sw = new StreamWriter(cs);
                sw.Write(inputString);
                sw.Flush();
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
            }
            finally
            {
                if (sw != null) sw.Close();
                if (cs != null) cs.Close();
                if (ms != null) ms.Close();
            }
        }

        /// <summary>
        /// DES解密。
        /// </summary>
        /// <param name="inputString">输入字符串。</param>
        /// <returns>解密后的字符串。</returns>
        public static string DESDecrypt(string inputString)
        {
            MemoryStream ms = null;
            CryptoStream cs = null;
            StreamReader sr = null;

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                ms = new MemoryStream(Convert.FromBase64String(inputString));
                cs = new CryptoStream(ms, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);
                sr = new StreamReader(cs);
                return sr.ReadToEnd();
            }
            finally
            {
                if (sr != null) sr.Close();
                if (cs != null) cs.Close();
                if (ms != null) ms.Close();
            }
        }


        private static string kay = "yjimspoi";
        private static string kiv = "99008855";
        /// <summary>
        /// 加密方法
        /// </summary>
        /// <param name="encryptionStr">需要加密字符串</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string encryptionStr)
        {
            string key = GetKey(kay);
            string iv = GetKey(kiv);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            //把字符串放到byte数组中

            //原来使用的UTF8编码，我改成Unicode编码了，不行
            byte[] byt = Encoding.Default.GetBytes(encryptionStr);

            //建立加密对象的密钥和偏移量
            //使得输入密码必须输入英文文本
            DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, DES.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            ret.ToString();
            return ret.ToString();
        }

        /// <summary> 
        /// 解密方法
        /// </summary>
        /// <param name="decryptStr">需要解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string decryptStr)
        {
            string key = GetKey(kay);
            string iv = GetKey(kiv);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            byte[] byt = new byte[decryptStr.Length / 2];
            for (int x = 0; x < decryptStr.Length / 2; x++)
            {
                int i = (Convert.ToInt32(decryptStr.Substring(x * 2, 2), 16));
                byt[x] = (byte)i;
            }

            //建立加密对象的密钥和偏移量，此值重要，不能修改
            DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(iv);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, DES.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(byt, 0, byt.Length);
            cs.FlushFinalBlock();
            //建立StringBuild对象，CreateDecrypt使用的是流对象，必须把解密后的文本变成流对象
            StringBuilder ret = new StringBuilder();
            var str = System.Text.Encoding.Default.GetString(ms.ToArray());
            return str;
        }

        private static string GetKey(string key)
        {
            if (key.Length < 8)//补0
            {
                var count = 8 - key.Length;
                for (int i = 0; i < count; i++)
                {
                    key += "0";
                }
            }
            else if (key.Length > 8)
            {
                key = key.Substring(0, 8);
            }
            return key;
        }
        #endregion 
    }
}
